import 'dart:async';

import 'package:baselib/base/base_responce.dart';
import 'package:baselib/util/common_apiservice.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/model/forget_pass_bean.dart';
import 'package:flutter_app/util/urls.dart';
import 'package:flutter_app/widget/login_dialog.dart';
import 'package:get/get.dart';
import 'package:toast/toast.dart';
class ForgetPassController extends GetxController{
  var userPhone="".obs;
  var userPhoneErrortext="".obs;
  var userCode="".obs;
  var start=120.obs;
  var userNewPass="".obs;
  var userAgainPass="".obs;


  ///修改密码
  Future<void> updatePass(BuildContext context) async{
      if(userPhone.value.isEmpty){
        return;
      }
      if(userCode.value.isEmpty){
        return;
      }
      if(userNewPass.value.isEmpty){
        return;
      }
      if(userAgainPass.value.isEmpty){
        return;
      }
      var body = {
        'tel': userPhone.value,
        'code': userCode.value,
        'passwdone': userNewPass.value,
        'passwdtwo': userAgainPass.value
      };
      BaseResponce responce = await CommonApiService.requestPost(
          Get.context,
          url: Urls.forgetpwd,
          data: body
      );
      if(responce.code==200){
        ForgetPassBean bena=ForgetPassBean.fromJson(responce.data);
        if(bena.status=="success"){
          Get.back();
          showDialog(context: context,barrierDismissible:false,
              builder: (ctx)=>buildLoginDialog());
        }
      }else{
        Toast.show(responce.message, context, duration: Toast.LENGTH_LONG, gravity:  Toast.TOP,backgroundColor:Colors.red);
      }
  }

  Widget buildLoginDialog() =>Dialog(
    backgroundColor:Colors.white,
    elevation:5,
    shape:RoundedRectangleBorder(
        borderRadius:BorderRadius.all(Radius.circular(10))
    ),
    child:Container(
      width:480,
      height: 460,
      child: loginDialog(),
    ),);

  ///获取验证码
  Future<void> getSmsCode(BuildContext context) async{

    if (userPhone.isEmpty) {
      return;
    }

    var body = {
      'tel': userPhone.value,
    };
    BaseResponce responce = await CommonApiService.requestGet(
        Get.context,
        url: Urls.send_sms,
        data: body
    );
    if(responce.code==200){
      Toast.show(responce.message, context, duration: Toast.LENGTH_LONG, gravity:  Toast.TOP,backgroundColor:Colors.red);
      timer();
    }else{
      Toast.show(responce.message, context, duration: Toast.LENGTH_LONG, gravity:  Toast.TOP,backgroundColor:Colors.red);
    }
  }

  ///倒计时
  Timer _timer;
  bool isbegin = false;
  void timer() {
    if (isbegin) return;
    const oneSec = const Duration(seconds: 1); //间隔1秒
    _timer = new Timer.periodic(oneSec, (timer) {
      if (start < 1) {
        //如果小于1则停止倒计时
        start.value = 120;
        isbegin = false;
        timer.cancel();
      } else {
        isbegin = true;
        start = start - 1; //自减一
      }
    });
  }
}